package qj.tool.jna.support;

import java.awt.event.MouseEvent;
import java.util.concurrent.atomic.AtomicReference;

import qj.tool.build.BuildUtil;
import qj.tool.jna.KeyboardHandler;
import qj.ui.DesktopUI4;
import qj.util.ThreadUtil;
import qj.util.funct.F0;
import qj.util.funct.Fs;
import qj.util.funct.P0;
import qj.util.funct.P1;

public class MouseRepeater {
	public static void main(String[] args) {
		final P1<P1<F0<Boolean>>> async1f = ThreadUtil.async1F();
		final AtomicReference<P0> stopRef = new AtomicReference<P0>();
		final AtomicReference<P0> normalBtn = new AtomicReference<P0>();
		final AtomicReference<P0> fastBtn = new AtomicReference<P0>();
		final AtomicReference<P0> veryFastBtn = new AtomicReference<P0>();

		final P0[] normalClickF = {null};
		final P0[] fastClickF = {null};
		final P0[] veryFastClickF = {null};
		
		final P0 stopF = new P0() {public void e() {
			async1f.e(null);
			normalBtn.set(normalClickF[0]);
			fastBtn.set(fastClickF[0]);
			veryFastBtn.set(veryFastClickF[0]);
		}};
		
		normalClickF[0] = new P0() {public void e() {
			async1f.e(click(200));
			normalBtn.set(stopF);
			fastBtn.set(fastClickF[0]);
			veryFastBtn.set(veryFastClickF[0]);
		}};
		
		fastClickF[0] = new P0() {public void e() {
			async1f.e(click(30));
			normalBtn.set(normalClickF[0]);
			fastBtn.set(stopF);
			veryFastBtn.set(veryFastClickF[0]);
		}};
		
		veryFastClickF[0] = new P0() {public void e() {
			async1f.e(click(3));
			normalBtn.set(normalClickF[0]);
			fastBtn.set(fastClickF[0]);
			veryFastBtn.set(stopF);
		}};

		stopRef.set(stopF);
		normalBtn.set(normalClickF[0]);
		fastBtn.set(fastClickF[0]);
		veryFastBtn.set(veryFastClickF[0]);
		
		KeyboardHandler.mapPressed('Q', Fs.atomicP0(stopRef));
		KeyboardHandler.mapPressed('W', Fs.atomicP0(normalBtn));
		KeyboardHandler.mapPressed('E', Fs.atomicP0(fastBtn));
		KeyboardHandler.mapPressed('R', Fs.atomicP0(veryFastBtn));
	}

//	private static P0 sleep(final int sleepTime,
//			final P1<P1<F0<Boolean>>> async1f) {
////		final boolean[] clicking = 
//		return new P0() {public void e() {
//			if (sleepTime<=0) {
//				async1f.e(null);
//			} else {
//				async1f.e(new P1<F0<Boolean>>() {public void e(F0<Boolean> interrupted) {
//					while (!interrupted.e()) {
//						DesktopUI4.mouseClick(MouseEvent.BUTTON1);
//						ThreadUtil.sleep(sleepTime);
//					}
//				}});
//			}
//		}};
//	}
	
	private static P1<F0<Boolean>> click(final int sleepTime) {
		return new P1<F0<Boolean>>() {public void e(F0<Boolean> interrupted) {
			while (!interrupted.e()) {
				DesktopUI4.mouseClick(MouseEvent.BUTTON1);
				ThreadUtil.sleep(sleepTime);
			}
		}};
	}

	public static class Build {
		public static void main(String[] args) {
			BuildUtil.buildApp(MouseRepeater.class);
		}
	}
}
